// pages/baseinfo/baseinfo.js
import toast from '../../common/service/toast-service';
import Upload from '../../utils/image-tool';
import {getLength} from '../../utils/string-util';
import {showAlertModel} from '../../common/service/alter-service';
import {getUserInfo, saveUserData} from '../../common/service/user-service';
import {getWxUserInfo} from '../../common/service/system-service';
import {navigateTo, navigateBack} from '../../common/service/page-service';
import {updateUser} from '../../data-model/model-baseinfo';
import {eventBusGetter} from '../../utils/eventbus';
import {EVENT_BUS_KEY} from '../../common/constants';

/**
 * 表单数据拼接 公司行业职位如果在userInfo中本身存在 则不可编辑
 * 如果baseRank!==200 则姓名不可编辑
 */
let pageConf = {

    data: {
        userId: '',
        needShowModal: true,
        avatarUrl: '',
        username: '', // 默认用户名
        mobile: '', // 帐号, 非userInfo中的mobile字段, mobile是联系方式
        positionName: '', // 职位名称
        companyName: '', // 公司名称
        industry: '',
        nameEditable: true, // 姓名
        companyEditable: true, // 公司
        positionEditable: true, // 职位
        industryEditable: true, // 行业 是否可编辑
        hasModifyAvatar: false // 已经修改了头像 或用户有姓名和头像 onShow时不需要再修改
    },
    onLoad (options) {
        this.initView();
    },
    onShow () {
        let that = this;
        let userInfo = getUserInfo();
        // 获取微信头像
        // 只有当用户身份为200 且用户没有头像和姓名时 且没取消过授权弹窗 才重新设置微信头像昵称
        if (userInfo && (userInfo.baseRank === 200 && !userInfo.name && !userInfo.userAvatar) && this.data.needShowModal && !this.data.hasModifyAvatar) {
            console.log('完善个人信息页面, 请求授权, 展示微信信息');
            getWxUserInfo()
                .then(res => {
                    that.setData({
                        needShowModal: false,
                        username: res.userInfo.nickName,
                        avatarUrl: res.userInfo.avatarUrl
                    });
                })
                .catch(err => {
                    console.log(err);
                    if (err.errMsg === ('getUserInfo:fail auth deny' || 'getUserInfo:fail:auth deny')) {
                        console.log('用户拒绝授权');
                    }
                });
        }
    },
    // 初始化页面布局
    initView () {
        let userInfo = getUserInfo();
        console.log('完善个人信息页面初始化', userInfo);
        if (userInfo) {
            this.setData({
                userId: userInfo.userId,
                username: userInfo.name,
                mobile: userInfo.account,
                avatarUrl: userInfo.userAvatar ? userInfo.userAvatar : '',
                companyName: userInfo.userCompany ? userInfo.userCompany : '',
                positionName: userInfo.userPosition ? userInfo.userPosition : '',
                industry: userInfo.industry ? userInfo.industry : '',
                nameEditable: userInfo.baseRank === 200,
                companyEditable: !userInfo.userCompany,
                positionEditable: !userInfo.userPosition,
                industryEditable: !userInfo.industry
            });
        }
    },
    onSwitchUserClick () {
        // 弹出modal提示 点击确定跳转到登录页
        let mobile = this.data.mobile;
        showAlertModel({
            title: '切换当前帐号',
            content: `切换后你的学习数据将会更新，你可以登录${mobile}重新找回当前数据`,
            cancelText: '取消',
            confirmText: '确定'
        }).then(res => {
            if (res.confirm) {
                navigateTo({url: '/pages/login/login?afterSwitchHome=' + true});
            }
        }).catch(err => {
            console.log('点击取消', err);
        });
    },
    /** 修改头像 */
    onClickAvatar () {
        let that = this;
        that.setData({
            hasModifyAvatar: true
        });
        let upload = new Upload();
        upload.chooseImageUpload(1, undefined, (res) => {
            if (res.success) {
                that.setData({
                    avatarUrl: res.imgUrl
                });
            }
        });
    },

    /** 点击确定 表单提交 */
    basicFormSubmit (fromData) {
        // let formId = fromData.detail.formId;
        // TODO formId
        let that = this;
        let obj = fromData.detail.value;

        // region 表单验证
        if (!that.data.avatarUrl) {
            toast.showLoadingToast('请上传头像');
            return;
        }
        if (obj.userName.length === 0) {
            toast.showLoadingToast('请输入姓名');
            return;
        }
        if (getLength(obj.userName) < 4) {
            toast.showLoadingToast('姓名最少2个字');
            return;
        }
        if (obj.companyName.length === 0) {
            toast.showLoadingToast('请输入公司');
            return;
        }
        if (getLength(obj.companyName) > 60) {
            toast.showLoadingToast('公司最多30字');
            return;
        }
        if (obj.companyPosition.length === 0) {
            toast.showLoadingToast('请输入职位');
            return;
        }
        if (getLength(obj.companyPosition) > 20) {
            toast.showLoadingToast('职位最多10字');
            return;
        }
        if (obj.companyIndustry.length === 0) {
            toast.showLoadingToast('请输入行业');
            return;
        }
        if (getLength(obj.companyIndustry) > 40) {
            toast.showLoadingToast('行业最多20字');
            return;
        }
        // endregion

        // region 表单数据拼接 公司行业职位如果在userInfo中本身存在 则不拼接
        let postParam = {
            'userId': this.data.userId,
            'userName': obj.userName,
            'userCompany': obj.companyName,
            'userPosition': obj.companyPosition,
            'industry': obj.companyIndustry,
            'userAvatar': that.data.avatarUrl
        };
        if (!this.data.companyEditable) {
            delete postParam['userCompany'];
        }
        if (!this.data.positionEditable) {
            delete postParam['userPosition'];
        }
        if (!this.data.industryEditable) {
            delete postParam['industry'];
        }
        // endregion

        // 执行提交表单流程
        toast.showLoading();
        updateUser(postParam)
            .then(userInfo => {
                console.log(userInfo);
                saveUserData(userInfo);
                // 发送通知 '我的' 页面更新
                eventBusGetter().$emit(EVENT_BUS_KEY.REFRESH_MY_COURSE);
                navigateBack({delta: 1});
                toast.hideLoading();
            })
            .catch(err => {
                toast.hideLoading();
                console.log('更新信息失败', err);
                if (err.header && err.header.msg) {
                    toast.showLoadingToast(decodeURIComponent(err.header.msg));
                } else {
                    toast.showLoadingToast('更新信息失败');
                }
            });
    }
};
Page(pageConf);
